import { defineEventHandler } from "h3";
import { getUserById } from "../../database/services/userService";

export default defineEventHandler(async (event) => {
  try {
    // 从认证中间件中获取用户信息
    const currentUser = event.context.user;
    
    if (!currentUser) {
      throw createError({
        statusCode: 401,
        statusMessage: "用户未认证"
      });
    }

    // 根据用户ID获取完整的用户信息
    const user = await getUserById(currentUser.id);
    
    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: "用户不存在"
      });
    }

    // 返回用户信息（不包含密码）
    const { password, ...userInfo } = user.toJSON();
    
    return {
      success: true,
      data: userInfo
    };
  } catch (error) {
    console.error("获取用户信息时出错:", error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: "获取用户信息失败"
    });
  }
});
